package org.light.verb;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.light.core.Verb;
import org.light.core.Writeable;
import org.light.domain.Domain;
import org.light.domain.Field;
import org.light.domain.JavascriptBlock;
import org.light.domain.JavascriptMethod;
import org.light.domain.Method;
import org.light.domain.Signature;
import org.light.domain.Statement;
import org.light.domain.Type;
import org.light.domain.Var;
import org.light.easyui.EasyUIPositions;
import org.light.exception.ValidateException;
import org.light.generator.NamedStatementGenerator;
import org.light.generator.NamedStatementListGenerator;
import org.light.utils.InterVarUtil;
import org.light.utils.MybatisSqlReflector;
import org.light.utils.PgsqlReflector;
import org.light.utils.StringUtil;
import org.light.utils.WriteableUtil;

public class FindById extends Verb implements EasyUIPositions {
	protected Set<Field> deniedFields = new TreeSet<>();
	
	@Override
	public Method generateDaoImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(
					"Find" + this.domain.getStandardName() + "By" + this.domain.getDomainId().getCapFirstFieldName());
			method.setNoContainer(false);
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getDomainId().getLowerFirstFieldName(),this.domain.getDomainId().getFieldType()));
			method.setReturnType(new Type(this.domain.getDomainSuffix()+"."+this.domain.getType()));
			
			List<Writeable> sList = new ArrayList<Writeable>();
			
			if (StringUtil.isBlank(this.getDbType())||this.getDbType().equalsIgnoreCase("MariaDB")||this.getDbType().equalsIgnoreCase("MySQL")) {
				sList.add(new Statement(1000L,1,"sql := \""+MybatisSqlReflector.generateFindByIdStatementWithDeniedFields(domain,this.deniedFields)+"\""));
			}else if (this.getDbType().equalsIgnoreCase("PostgreSQL")||this.getDbType().equalsIgnoreCase("pgsql")) {
				sList.add(new Statement(1000L,1,"sql := \""+ PgsqlReflector.generateFindByIdStatementWithDeniedFields(domain,this.deniedFields)+"\""));
			}				
			
			sList.add(new Statement(2000L,1,"stmt, err := db.Prepare(sql)"));
			sList.add(new Statement(3000L,1,"if err != nil {"));
			sList.add(new Statement(4000L,2,"panic(err)"));
			sList.add(new Statement(5000L,1,"}"));
			sList.add(new Statement(6000L,1,"row := stmt.QueryRow("+this.domain.getDomainId().getLowerFirstFieldName()+")"));
			sList.add(new Statement(7000L,1,"var "+this.domain.getLowerFirstDomainName()+" "+this.domain.getDomainSuffix()+"."+this.domain.getCapFirstDomainNameWithSuffix()+""));
			long serial = 8000L;
			
			for (Field f:this.domain.getFieldsWithoutId()) {
				if (f.getFieldType().equalsIgnoreCase("image"))  sList.add(new Statement(serial,1,"var "+f.getLowerFirstFieldName()+" [] byte"));
				else sList.add(new Statement(serial,1,"var "+f.getLowerFirstFieldName()+" "+ f.getFieldType()));
				serial += 1000L;
			}
			StringBuilder sb = new StringBuilder();
			for (Field f:this.domain.getFields()) {
				sb.append("&").append(f.getLowerFirstFieldName()).append(",");
			}
			String fieldsQuery = sb.toString();
			if (fieldsQuery.endsWith(",")) fieldsQuery=fieldsQuery.substring(0,fieldsQuery.length()-1);

			sList.add(new Statement(serial,0,""));
			sList.add(new Statement(serial+1000L,1,"err = row.Scan("+fieldsQuery+")"));
			sList.add(new Statement(serial+2000L,1,"if err != nil {"));
			sList.add(new Statement(serial+3000L,2,"panic(err)"));
			sList.add(new Statement(serial+4000L,1,"}"));
			serial += 5000L;
			for (Field f:this.domain.getFields()) {
				sList.add(new Statement(serial,1,""+this.domain.getLowerFirstDomainName()+".Set"+f.getCapFirstFieldName()+"("+f.getLowerFirstFieldName()+")"));
				serial += 1000L;
			}
			sList.add(new Statement(serial,1,"return "+this.domain.getLowerFirstDomainName()+""));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(
					"Find" + this.domain.getStandardName() + "By" + this.domain.getDomainId().getCapFirstFieldName());
			method.setReturnType(new Type(this.domain.getDomainSuffix()+"."+this.domain.getType()));
			method.addSignature(new Signature(1, "db","*sql.DB"));
			method.addSignature(new Signature(2, this.domain.getDomainId().getFieldName(),
					this.domain.getDomainId().getClassType()));
			return method;
		}
	}
	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(
					"Find" + this.domain.getStandardName() + "By" + this.domain.getDomainId().getCapFirstFieldName());
			method.setReturnType(new Type(this.domain.getDomainSuffix()+"."+this.domain.getType()));
			method.addSignature(new Signature(1, this.domain.getDomainId().getFieldName(),
					this.domain.getDomainId().getClassType()));
			method.setThrowException(true);

			return method;
		}
	}
	@Override
	public Method generateServiceImplMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(
					"Find" + this.domain.getStandardName() + "By" + this.domain.getDomainId().getCapFirstFieldName());
			method.addSignature(new Signature(1, this.domain.getDomainId().getLowerFirstFieldName(),this.domain.getDomainId().getFieldType()));
			method.setReturnType(new Type(this.domain.getDomainSuffix()+"."+this.domain.getType()));

			Method daomethod = this.generateDaoMethodDefinition();

			List<Writeable> list = new ArrayList<Writeable>();
			list.add(new Statement(1000L,1,"db := database.DB"));
			list.add(new Statement(2000L, 1, "return "
					+ daomethod.generateStandardDaoImplCallString(this.domain.getDaoimplSuffix())));
			method.setMethodStatementList(WriteableUtil.merge(list));

			return method;
		}
	}

	public FindById() {
		super();
		if (this.domain != null)
			this.setVerbName(
					"Find" + this.domain.getStandardName() + "By" + this.domain.getDomainId().getCapFirstFieldName());
		else
			this.setVerbName("FindById");
		this.setLabel("根据序号查找");
	}

	public FindById(Domain domain) throws ValidateException{
		super();
		this.domain = domain;
		this.denied = domain.isVerbDenied("FindById");
		this.setVerbName("Find" + this.domain.getStandardName() + "By"
				+ StringUtil.capFirst(this.domain.getDomainId().getCapFirstFieldName()));
		this.setLabel("根据序号查找");
		if  (domain.getLanguage().equalsIgnoreCase("english"))  this.setLabel("FindById");
	}

	@Override
	public Method generateControllerMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			Method method = new Method();
			method.setStandardName(
					"Find" + this.domain.getStandardName() + "By" + this.domain.getDomainId().getCapFirstFieldName());
			method.addSignature(new Signature(1,"c","*gin.Context"));
			
			List<Writeable> sList = new ArrayList<Writeable>();
			sList.add(new Statement(1000L,1,"idStr := c.PostForm(\""+this.domain.getDomainId().getLowerFirstFieldName()+"\")"));
			sList.add(new Statement(2000L,1,this.domain.getDomainId().getLowerFirstFieldName()+", _ := strconv.ParseInt(idStr, 10, 64)"));
			sList.add(new Statement(3000L,1,this.domain.getLowerFirstDomainName()+" := "+this.domain.getServiceimplSuffix()+".Find"+this.domain.getCapFirstDomainName()+"By"+this.domain.getDomainId().getCapFirstFieldName()+"("+this.domain.getDomainId().getLowerFirstFieldName()+")"));
			sList.add(new Statement(4000L,1,"SendResponse(c, nil, "+this.domain.getLowerFirstDomainName()+", 0, true)"));
			method.setMethodStatementList(WriteableUtil.merge(sList));
			return method;
		}
	}
	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		if (this.denied)
			return null;
		else {
			return null;
		}
	}
	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		if (this.denied)
			return null;
		else {
			return null;
		}
	}

	public Set<Field> getDeniedFields() {
		return deniedFields;
	}

	public void setDeniedFields(Set<Field> deniedFields) {
		this.deniedFields = deniedFields;
	}

}
